package com.zzl.car.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.github.pagehelper.PageInfo;
import com.zzl.car.context.ZdpJwtUserContext;
import com.zzl.car.entity.AliPayBean;
import com.zzl.car.entity.CarDetailInfo;
import com.zzl.car.entity.CarOrder;
import com.zzl.car.exception.ZdpException;
import com.zzl.car.service.CarDetailInfoService;
import com.zzl.car.service.CarOrderService;
import com.zzl.car.util.AliPayUtil;
import com.zzl.car.util.ZdpJwtUtil;
import com.zzl.car.zdpAnnotation.NotResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/*
* 用户管理个人订单
* 查看订单
* 分页
* */
@RestController
public class ZdpUserOrderController {

    @Autowired
    private CarOrderService carOrderService;
    @Autowired
    private AliPayUtil aliPayUtil;
    @Autowired
    private CarDetailInfoService carDetailInfoService;
    /*
    * 点击订单管理，默认显示全部的订单
    *   传入参数 state : 0 1 2 3 : 获取到不同状态的订单
    * 默认获取全部订单
    *
    @RequestBody Map<String,Object> data
    * Integer page = (Integer) data.getOrDefault("pageNum",1);
        Integer state = (Integer) data.getOrDefault("state",-1);
    * * */
    @GetMapping("/getOrder")
    public PageInfo<CarOrder> getAllOrder(@RequestParam(value="pageNum",defaultValue = "1") Integer page,
                                          @RequestParam(value="state",defaultValue = "-1")Integer state){
        //telephone ---> jwt上下文对象来取
        System.out.println(state);
        String telephone = ZdpJwtUserContext.getCurrentName();
        return carOrderService.getAllOrderByUserAndPage(telephone,page,5,state);
    }

    /*
    * 新建订单
    * */
    @PostMapping("/createOrder")
    public CarOrder createNewOrder(@RequestBody CarOrder carOrder){
        System.out.println(carOrder);
        carOrder = carOrderService.createNewCarOrder(carOrder);
        return carOrder;
    }

    /*
    * 用户支付订单
    * */
    @NotResponseBody
    @PostMapping("/userOrderPay")
    public String userOrderPay(@RequestBody AliPayBean aliPayBean){
        System.out.println(aliPayBean);
        String pay = null;
        try {
            pay = aliPayUtil.pay(aliPayBean);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return pay;
    }
    /*
    * 支付的异步通知函数
    * */
    @PostMapping("notifyurl")
    public String notifyurl(HttpServletRequest request) throws UnsupportedEncodingException {
        System.out.println("==========notifyurl===========");
        //订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        // 付款金额
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
        // 支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        // 交易说明
        //String cus = new String(request.getParameter("body").getBytes("ISO-8859-1"), "UTF-8");
        // 交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
        //商品名称
        String subject = new String(request.getParameter("subject").getBytes("ISO-8859-1"),"UTF-8");
        if(trade_status.equals("TRADE_SUCCESS")){
            // 交易成功，改变订单状态
            CarOrder carOrder = carOrderService.getOrderByOrderNumber(out_trade_no);
            // 更改订单状态
            carOrder.setState(1);
            // 车辆状态也要改变吧 由0 ->1
            carOrder.getCarDetailInfo().setState("1");
            // 数据库中车辆状态也要改变
            // 先更新车辆，再更新缓存吧
            carDetailInfoService.updateCarDetailInfo(carOrder.getCarDetailInfo());
            carOrderService.updateCarOrder(carOrder);
            return "notifyUrl";
        }else{
            return "失败";
        }

    }

    /*
    * 用户取消预定中订单 ,修改订单状态而已 缓存也只需要改变state
    * 车辆状态也要改变吧
    * 分页内容也要变吧
    * */
    @PostMapping("/cancelOrderBooking")
    public CarOrder cancelCarOrderBooking(@RequestBody CarOrder carOrder){
        //
        System.out.println(carOrder);
        return carOrderService.cancelCarOrderBooking(carOrder);
    }

    /*
    * 用户取消租赁中订单，需要计算退款金额
    * */
    @PostMapping("/cancelOrderUsing")
    public CarOrder cancelOrderUsing(@RequestBody Map<String,Object>data) throws ParseException {
        // 因为传入了两个值，值以json格式包装在请求体中
        //@RequestBody 一次性将请求体中的数据拿到
        // 若值为数据实体类，那么会被解析为LinkedHashMap 所以我们需要将该值手动转为实体类对象
        // 先转json 再转实体类
        Object t = data.get("carOrder");
        String s = JSON.toJSONString(t);
        CarOrder carOrder = JSON.parseObject(s,CarOrder.class);
        String tt = (String) data.get("time");
        // 前端传来的json字符串带T
        tt = tt.replace("T", " ");
        Date time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(tt);
        System.out.println(time);
        return carOrderService.cancelCarOrderUsing(carOrder, time);
    }

    /*
    * 用户提前还车
    * */
    @PostMapping("/advanceReturnCar")
    public String advanceReturnCar(@RequestBody Map<String,Object>data){
        // 传入还车时间和那个订单号
        String carOrderNumber = (String) data.get("orderNumber");
        Long time = (Long)data.get("advanceTime");
        carOrderService.advanceReturnCar(carOrderNumber,time);
        return "已提交提前还车申请";
    }
    /*
    * 用户续租申请
    * 传入还车时间和订单号
    * 不直接传入订单？ ----> 转来转去的麻烦死了
    * */
    @PostMapping("/continueRentCar")
    public String continueRentCar(@RequestBody Map<String,Object>data){
        String carOrderNumber = (String) data.get("orderNumber");
        Long time = (Long)data.get("continueRentTime");
        carOrderService.continueRentCar(carOrderNumber,time);
        return "已提交续租申请";
    }

    /*
    * 提前还车轮询
    * */
    @PostMapping("/getAdvanceReturningByUser")
    public CarOrder getAdvanceReturningByUser(){
            return carOrderService.getAdvanceReturningByUser();
    }

    /*
    * 续租申请轮询
    * */
    @PostMapping("/getContinueRentCarByUser")
    public CarOrder getContinueRentCarByUser(){
        return null;
    }

}
